package es.esi.gemde.methodmanager.service.handlers;

import java.util.Vector;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.widgets.Shell;

import es.esi.gemde.methodmanager.CommandConstants;
import es.esi.gemde.methodmanager.service.impl.CommandParametersRegistry;
import es.esi.gemde.methodmanager.service.ui.SelectEObjectDialog;

public class SelectElementFromEObjectCommandHandler extends AbstractHandler {
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String eobject = event.getParameter(CommandConstants.EOBJECT_PARAM_ID);
		String addToList = event.getParameter(CommandConstants.ADDTOLIST_PARAM_ID);
		String listObjID = event.getParameter(CommandConstants.LIST_PARAM_ID);
		
		if (eobject == null || CommandParametersRegistry.instance().getParam(eobject) == null || !(CommandParametersRegistry.instance().getParam(eobject) instanceof EObject)) {
			throw new ExecutionException("Provided EObject is not valid.");
		}
		
		EObject root = (EObject) CommandParametersRegistry.instance().getParam(eobject);
		
		SelectEObjectDialog d = new SelectEObjectDialog(new Shell(), root);
		if (d.open() == Dialog.OK) {
			EObject selection = d.getSelectedEObject();
			
			if (addToList != null && addToList.equals("true")) {
				Object listObj = CommandParametersRegistry.instance().getParam(listObjID);
				if (listObj == null || !(listObj instanceof Vector<?>)) {
					Vector<EObject> list = new Vector<EObject>();
					list.add(selection);
					String objString = list.toString().indexOf(' ') == -1 ? list.toString() : list.toString().substring(0, list.toString().indexOf(' '));
					CommandParametersRegistry.instance().putParam(objString, list);
					return objString;
				}
				else {
					@SuppressWarnings("unchecked")
					Vector<EObject> list = (Vector<EObject>) listObj;
					list.add(selection);
					String objString = list.toString().indexOf(' ') == -1 ? list.toString() : list.toString().substring(0, list.toString().indexOf(' '));
					CommandParametersRegistry.instance().putParam(objString, list);
					return objString;
				}
			}
			else {
				String objString = selection.toString().indexOf(' ') == -1 ? selection.toString() : selection.toString().substring(0, selection.toString().indexOf(' '));
				CommandParametersRegistry.instance().putParam(objString, selection);
				return objString;
			}
		}
		
		return null;
	}

}